define([
    'underscore',
    'backbone',
    'template',
    '../collection/goods',
    '../model/goods',
    '../view/goods',
    'text!../tmpl/seller.html'
],function(_,Backbone,Template,GoodsCollection,GoodsModel,GoodsView,SellerTmpl){
    var SellerView = Backbone.View.extend({
        tagName:'div',
        className:'seller-item',
        template:Template.compile(SellerTmpl),
        initialize:function(option){
            this.collection = new GoodsCollection(option.dataset);
            this.seller_info = option.seller_info;

            //重要，绑定当前对象的render,unrender,不然model.bind时，无法调用当前对象的的方法中的this
            _.bindAll(this, 'render', 'removeItem');

            //model内容改变时，重新渲染视图

            this.collection.on('remove',this.removeItem);


        },

        //事件绑定
        events:{
            'click .seller-all':'seller_all'

        },
        //全选本店商品
        seller_all:function (e,obj,c) {

            var checked =this.$('.seller-all').prop('checked');
            _(this.collection.models).map(function (model) {
                model.set('checked',checked);
            },this);
        },
        /*添加新的项*/
        appendItem:function (item) {
            var itemView = new GoodsView({
                model: item
            });
            this.$('.goods-list').append(itemView.render().el)
        },
        removeItem:function (item,collection) {
            if(collection.length==0){
                this.unrender();
            }
        },
        //输出渲染
        render: function () {
            var self = this;
            self.$el.html(self.template(self.seller_info));
            //输出列表信息
            _(this.collection.models).each(function(item){ // in case collection is not empty
                self.appendItem(item);
            }, this);
            return self;
        },
        unrender:function () {
            this.$el.remove();
        }
    });
    return SellerView;
});